package com.bree.erp.data.xls.imp.sheet;

import javax.persistence.EntityManager;

import jxl.Sheet;

import com.bree.erp.data.xls.imp.AbstractSheet;
import com.bree.erp.entity.BrandSeller;
import com.bree.erp.entity.MasterItem;
import com.bree.erp.entity.Unit;
import com.bree.erp.service.BrandSellerService;
import com.bree.erp.service.MasterItemService;
import com.bree.erp.service.PartUnitService;
import com.bree.erp.service.UnitService;
import com.bree.erp.service.stateless.BrandSellerServiceBean;
import com.bree.erp.service.stateless.MasterItemServiceBean;
import com.bree.erp.service.stateless.PartUnitServiceBean;
import com.bree.erp.service.stateless.UnitServiceBean;

public class MasterListSheet extends AbstractSheet {

	public MasterListSheet(Sheet sheet) {
		super(sheet);
	}

	@Override
	public void importSheet(EntityManager em) {
		Sheet sheet = this.getSheet();

		MasterItemService miService = new MasterItemServiceBean(em);
		BrandSellerService bsService = new BrandSellerServiceBean(em);
		UnitService unitService = new UnitServiceBean(em);
		PartUnitService puService = new PartUnitServiceBean(em);

		for (int row = 1; row < sheet.getRows(); row++) {

			em.getTransaction().begin();

			String name = sheet.getCell(0, row).getContents().trim();
			String description = sheet.getCell(1, row).getContents().trim();
			String unitStr = sheet.getCell(2, row).getContents().trim();
			String brand = sheet.getCell(3, row).getContents().trim();
			String partNum = sheet.getCell(4, row).getContents().trim();

			BrandSeller seller = bsService.findByName(brand);

			MasterItem item = miService.findByName(name);
			if (item == null) {
				miService.create(seller, name, description);
			}
			
			em.getTransaction().commit();
			

			em.getTransaction().begin();
			
			item = miService.findByName(name);
			Unit unit = unitService.read(unitStr);
			
			puService.create(item, unit, partNum);

			em.getTransaction().commit();

		}

	}

}
